package com.itheima.web.controller.store;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.store.Catalog;
import com.itheima.domain.store.Company;
import com.itheima.domain.store.Question;
import com.itheima.utils.BeanUtil;
import com.itheima.web.controller.BaseServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @program: mm
 * @description:
 * @author: zhanghz001
 * @create: 2020-10-15 14:06
 **/
// uri:/store/question?operation=list
@WebServlet("/store/question")
public class QuestionServlet extends BaseServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String operation = request.getParameter("operation");
        if ("list".equals(operation)) {
            this.list(request, response);
        } else if ("toAdd".equals(operation)) {
            this.toAdd(request, response);
        } else if ("save".equals(operation)) {
            try {
                this.save(request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("toEdit".equals(operation)) {
            this.toEdit(request, response);
        } else if ("edit".equals(operation)) {
            try {
                this.edit(request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("delete".equals(operation)) {
            this.delete(request, response);
        } else if ("downloadReport".equals(operation)) {
            this.downloadReport(request, response);
        }
    }

    private void downloadReport(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //返回的数据类型为xlsx类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = new String("测试文件名称1.xlsx".getBytes(), "iso-8859-1");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        //获取输出流
        // questionService.getReport();
        ByteArrayOutputStream report = questionService.getReport();
        //获取产生响应的流对象
        ServletOutputStream stream = response.getOutputStream();
        //写入到servlet对应的输出流中
        report.writeTo(stream);
        //输出流刷新
        report.flush();
        stream.flush();
        // stream.close();
        report.close();
    }

    private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //进入列表页
        //获取数据
        int page = 1;
        int size = 5;
        if (StringUtils.isNotBlank(request.getParameter("page"))) {
            page = Integer.parseInt(request.getParameter("page"));
        }
        if (StringUtils.isNotBlank(request.getParameter("size"))) {
            size = Integer.parseInt(request.getParameter("size"));
        }
        PageInfo all = questionService.findAll(page, size);
        //将数据保存到指定的位置
        request.setAttribute("page", all);
        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/store/question/list.jsp").forward(request, response);
    }

    private void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Company> companyList = companyService.findAll();
        List<Catalog> catalogList = catalogService.findAll();
        request.setAttribute("companyList", companyList);
        request.setAttribute("catalogList", catalogList);
        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/store/question/add.jsp").forward(request, response);
    }

    private void save(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //将数据获取到，封装成一个对象
        if (ServletFileUpload.isMultipartContent(request)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            //form表单提交过来的文件数据
            List<FileItem> items = upload.parseRequest(request);
            Question question = BeanUtil.fillBean(items, Question.class);
            //调用业务层接口save
            String id = questionService.save(question);

            for (FileItem item : items) {
                if (!item.isFormField()) {
                    item.write(new File(getServletContext().getRealPath("upload")
                            , id));
                }
            }
        }
        //跳转回到页面list
        response.sendRedirect(request.getContextPath() + "/store/question?operation=list");
    }

    private void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //查询要修改的数据findById
        String id = request.getParameter("id");
        Question question = questionService.findById(id);
        //将数据加载到指定区域，供页面获取
        request.setAttribute("question", question);

        List<Company> companyList = companyService.findAll();
        List<Catalog> catalogList = catalogService.findAll();
        request.setAttribute("companyList", companyList);
        request.setAttribute("catalogList", catalogList);

        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/store/question/update.jsp").forward(request, response);
    }

    private void edit(HttpServletRequest request, HttpServletResponse response) throws Exception {

        //将数据获取到，封装成一个对象
        if (ServletFileUpload.isMultipartContent(request)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            //form表单提交过来的文件数据
            List<FileItem> items = upload.parseRequest(request);
            Question question = BeanUtil.fillBean(items, Question.class);
            //调用业务层接口save
            questionService.update(question);

            for (FileItem item : items) {
                if (!item.isFormField()) {
                    item.write(new File(getServletContext().getRealPath("upload")
                            , question.getId()));
                }
            }
        }
        //跳转回到页面list
        //list(request,response);
        response.sendRedirect(request.getContextPath() + "/store/question?operation=list");
    }

    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //将数据获取到，封装成一个对象
        Question question = BeanUtil.fillBean(request, Question.class);
        //调用业务层接口save
        questionService.delete(question);
        //跳转回到页面list
        response.sendRedirect(request.getContextPath() + "/store/question?operation=list");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    private void testUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (ServletFileUpload.isMultipartContent(request)) {
            //创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //servlet文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //从request读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                //当前是否为文件表单
                if (!fileItem.isFormField()) {
                    fileItem.write(new File(getServletContext().getRealPath("upload"), fileItem.getName()));
                }
            }
        }

    }
}
